const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
};

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
};


/**
 * 判断双击函数，需要绑定在bindtap事件
 * @params {Object} that  当前上下文
 * @params {Event} e  当前事件
 * @params {Function} dbTapHandler  若触发双击的处理函数
 * @params {Function} tapHandler  若触发单击的处理函数
 */
const doubleTap = (that, e, dbTapHandler, tapHandler) => {
  if (!that.touchStartTime) {
    that.touchStartTime = e.timeStamp;
    tapHandler && tapHandler();     // 触发单击
    return;
  }
  else {
    if (!that.touchEndTime) {
      that.touchEndTime = e.timeStamp;
    }
    // 控制点击事件在350ms内触发，加这层判断是为了防止长按时会触发点击事件
    if (that.touchEndTime - that.touchStartTime < 350) {
      // 当前点击的时间
      const currentTime = e.timeStamp;
      const lastTapTime = that.lastTapTime;
      // 更新最后一次点击时间
      that.lastTapTime = currentTime;

      // 如果两次点击时间在300毫秒内，则认为是双击事件
      if (currentTime - lastTapTime < 300) {
        // 成功触发双击事件时，取消单击事件的执行
        clearTimeout(that.lastTapTimeoutFunc);
        dbTapHandler && dbTapHandler();     // 触发双击
      }
    }
    else {
      that.touchEndTime = null;
      tapHandler && tapHandler();     // 触发单击
    }
  }

}

module.exports = {
  formatTime,
  doubleTap
};
